import {Component, OnInit, ViewChild} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {ActivatedRoute, Router} from '@angular/router';
import {FormobjModel} from '../formobj.model';
import {PublicService} from '../../services/public.service';
import {BasePage} from '../../base.page';
import {MessageService} from 'primeng/components/common/messageservice';
import {ConfirmationService} from 'primeng/primeng';
import {AccessService} from '../access.service';
import {PUblicMethod} from '../../services/PUblicMethod';
import {CapacityDialogComponent} from '../../public/capacity-dialog/capacity-dialog.component';
import {UnaccessEquipTableComponent} from '../public/unaccess-equip-table/unaccess-equip-table.component';
import {AccessSelectEquipmentsComponent} from '../public/access-select-equipments/access-select-equipments.component';
import {TimeNotSameValidator} from '../../validator/validators';
import {EventBusService} from '../../services/event-bus.service';

@Component({
  selector: 'app-create-edit-access',
  templateUrl: './create-edit-access.component.html',
  styleUrls: ['./create-edit-access.component.scss']
})
export class CreateEditAccessComponent extends BasePage implements OnInit {

    @ViewChild('capacityDialog') capacityDialog: CapacityDialogComponent;
    @ViewChild('unaccessTable') unaccessTable: UnaccessEquipTableComponent;
    @ViewChild('accessSelectEquip') accessSelectEquip: AccessSelectEquipmentsComponent;
    controlDiaglog: boolean;
    formTitle = '创建申请单';
    myForm: FormGroup;
    formObj: FormobjModel;
    allTypes: Array<object>;
    allApprovals: Array<object>;
    zh: any;
    showAddMask: boolean = false;
    displayCapcity: boolean = false;
    minEndTime: Date;
    roomObj: object;
    statusCode: string;
    testapporve: any ;

    constructor(private fb: FormBuilder,
                private router: Router,
                private activedRouter: ActivatedRoute,
                private publicService: PublicService,
                private accessService: AccessService,
                private eventBusService: EventBusService,
                public messageService: MessageService,
                public confirmationService: ConfirmationService) {
        super(confirmationService, messageService);
    }

    ngOnInit() {
        this.formObj = new FormobjModel();
        this.zh = new PUblicMethod().initZh();
        this.initMyForm();
        this.formObj.plan_time_begin = PUblicMethod.formateEnrtyTime(new Date());
        this.formObj.plan_time_end = PUblicMethod.formateEnrtyTime(new Date());
        this.minEndTime = new Date();
        this.controlDiaglog = false;
        this.initCreator();
        this.getApprovals('1.1');
        this.initRegistrationType();
        // this.getQueryParams();
    }

    initMyForm = () => {
        this.myForm = this.fb.group({
            room_name: [null, Validators.required],
            timeGroup: this.fb.group({
                plan_time_begin: [null, Validators.required],
                plan_time_end: [null, Validators.required],
            }, {validator: TimeNotSameValidator}),
            content: '',
            approve: ''
        });
    };

    goBack = () => {
        this.router.navigate(['../overview'], {relativeTo: this.activedRouter});
        this.eventBusService.accessFlowCharts.next('');
    };

    showTreeDialog = () => {
        this.displayCapcity = true;
    };

    displayCapcityEmitter = event => {
        this.displayCapcity = event;
    };

    seledtedCapcityEmitter = event => {
        this.formObj.room_name = event['label'];
        this.formObj.room_did = event['did'];
        this.roomObj = event;
    };

    clearTreeDialog = () => {
        this.formObj.room_name = '';
        this.formObj.room_did = '';
        this.roomObj = {};
        this.capacityDialog.clearSelected();
    };

    initCreator = () => {
        this.publicService.getUser().subscribe(res => {
            this.formObj.creator = res['name'];
            this.formObj.creator_org = res['organization'];
        });
    };

    getApprovals = (oid?) => {
        this.publicService.getApprovers(oid).subscribe(res => {
            if (!res) {
                this.allApprovals = [];
            }else {
                let newArray = PUblicMethod.formateDepDropDown(res);
                this.allApprovals = newArray;
                this.formObj.approver = newArray[0]['value']['name'];
                this.formObj.approver_pid = newArray[0]['value']['pid'];
            }
            this.getQueryParams();
        });
    };


    initRegistrationType = () => {
        this.allTypes = [
            {
                'label': '出库',
                'value': '出库'
            },
            {
                'label': '入库',
                'value': '入库'
            }
        ];
        this.formObj.registration_type = '出库';
    };

    formatPerson = () => {
        if (typeof this.formObj.approver === 'object') {
            this.formObj.approver_pid = this.formObj.approver['pid'];
            this.formObj.approver = this.formObj.approver['name'];
        }
    }

    formatTime = () => {
        this.formObj.plan_time_begin = PUblicMethod.formateEnrtyTime(this.formObj.plan_time_begin)
        this.formObj.plan_time_end = PUblicMethod.formateEnrtyTime(this.formObj.plan_time_end);
    }

    startTimeSelected = t => {
        this.minEndTime = t;
    };

    // formgroup not nested formgroup can use this
    isFieldValid = (name) => {
        return PUblicMethod.isFieldValid(this.myForm, name);
    };

    // can listen fromgroup's error when formgroup nested formgroup
    isFieldFroupValid = (name?) => {
        return this.myForm.get('timeGroup').hasError('timematch');
    };

    // for button which is relative with one of formcontrol
    isFieldValueValid = (name) => {
        return PUblicMethod.isFieldValueValid(this.myForm, name);
    };

    // formgroup nested formgroup can use this
    isFieldGroupItemValid = (name) => {
        return PUblicMethod.isFieldGroupValid(this.myForm.get('timeGroup'), name);
    };

    save = () => {
        this.formatPerson();
        this.formatTime();
        this.formObj.devices = this.unaccessTable.tableDatas;
        (!this.formObj.sid || this.statusCode) && (this.requestSave());
        (this.formObj.sid) && (this.requestSaveAfterEdited());
    };

    requestSave = () => {
        this.accessService.requestSave(this.formObj).subscribe(res => {
            if ( res === '00000' ) {
                this.alert('保存成功')
                window.setTimeout(() => {
                    this.goBack();
                }, 1100);
            }else {
                this.alert(`保存失败 + ${res}`, 'error');
            }
        });
    };

    requestSaveAfterEdited = () => {
        this.accessService.requestSaveAfterEdited(this.formObj).subscribe(res => {
            if ( res === '00000' ) {
                this.alert('修改保存成功')
                window.setTimeout(() => {
                    this.goBack();
                }, 1100);
            }else {
                this.alert(`修改保存失败 + ${res}`, 'error');
            }
        });
    };

    submit = () => {
        this.formatPerson();
        this.formatTime();
        this.formObj.devices = this.unaccessTable.tableDatas;
        if (this.myForm.valid) {
            if (this.formObj.devices.length === 0) {
                this.alert('请先选择设备再进行提交', 'warn');
            }else {
                (!this.formObj.sid || this.statusCode) && (this.requestSubmit());
                (this.formObj.sid) && (this.requestSubmitAfterEidted());
            }
        }else {
            PUblicMethod.validateAllFormFields(this.myForm);
        }
    };

    requestSubmit = () => {
        this.accessService.requestSubmite(this.formObj).subscribe(res => {
            if ( res === '00000' ) {
                this.alert('提交成功')
                window.setTimeout(() => {
                    this.goBack();
                }, 1100);
            }else {
                this.alert(`提交失败 + ${res}`, 'error');
            }
        });
    };

    requestSubmitAfterEidted = () => {
      this.accessService.requestSubmitAfterEdit(this.formObj).subscribe(res => {
          if ( res === '00000' ) {
              this.alert('修改提交成功')
              window.setTimeout(() => {
                  this.goBack();
              }, 1100);
          }else {
              this.alert(`修改提交失败 + ${res}`, 'error');
          }
      });
    };

    importedEquip =  asset => {
        this.unaccessTable.tableDatas.push(asset);
      this.unaccessTable.dataSource = this.unaccessTable.tableDatas;
      this.unaccessTable.totalRecords = this.unaccessTable.dataSource.length;
      this.unaccessTable.tableDatas = this.unaccessTable.dataSource.slice(0,10);
        this.accessSelectEquip.searchObj.filter_asset_nos = this.filterUnaccessArrayOnlyId(this.unaccessTable.tableDatas); // 设备过滤
        this.getSelectedAnoArray(this.unaccessTable.tableDatas);
    };

    selectedEquipsEmitter = event => {
        event.forEach(arrayItem => {
            this.unaccessTable.tableDatas.push(arrayItem);
        });
        this.accessSelectEquip.searchObj.filter_asset_nos = this.filterUnaccessArrayOnlyId(this.unaccessTable.tableDatas); // 设备过滤
        this.getSelectedAnoArray(this.unaccessTable.tableDatas);
    };

    tableDataEmitter = dataArray => {
        this.unaccessTable.tableDatas = dataArray;
        this.accessSelectEquip.searchObj.filter_asset_nos = this.filterUnaccessArrayOnlyId(this.unaccessTable.tableDatas); // 设备过滤
        this.getSelectedAnoArray(dataArray);
    };

    filterUnaccessArrayOnlyId = (array): Array<any> => {
        let filterAssetAno = [];
        array.forEach(arryaItem => {
            filterAssetAno.push(arryaItem['asset_no']);
        });
        return filterAssetAno;
    };

    openEquipList = () => {
        this.controlDiaglog = true;
    };

    dcontrolDialogHandler = event => {
        this.controlDiaglog = event;
    };

    showAdd = () => {
        this.showAddMask = !this.showAddMask;
    };

    removeMask = bool => {
        this.showAddMask = bool;
    };
  removeEquipmenst = () => {
    for (let i = 0; i < this.unaccessTable.selectedCars3.length; i++) {
      this.unaccessTable.tableDatas = this.unaccessTable.tableDatas.filter(v => {
        return !(v['ano'] === this.unaccessTable.selectedCars3[i]['ano']);
      })
    }
    // this.accessSelectEquip.searchObj.filter_anos = this.getSelectedAnoArray(this.unaccessTable.tableDatas);
  }

    getQueryParams = () => {
        this.activedRouter.queryParams.subscribe(params =>  {
            (params['sid'])  && this.requestMesageBySid(params['sid']);
            (params['status_code']) && (this.statusCode = params['status_code']);
            (params['status']) && (this.eventBusService.accessFlowCharts.next(params['status']));
            (params['sid'] && params['status'])  && this.requestMesageBySid(params['sid']);
        });
    };

    requestMesageBySid = id => {
        this.accessService.getMesageBySid(id).subscribe(res => {
            if (res['errcode'] === '00000') {
               this.formObj = new FormobjModel(res['data']);
                (res['data']['approver_pid']) && this.filterSelectedApporve(this.allApprovals, res['data']['approver_pid']);
                res['data']['devices'] ? this.unaccessTable.tableDatas = res['data']['devices'] : this.unaccessTable.tableDatas = [];
                (res['data']['devices'] && res['data']['devices']['length'] > 0) && this.getSelectedAnoArray(res['data']['devices']);
            }else {
                this.alert(`获取出入单信息失败 + ${res['errmsg']}`, 'error');
            }
        });
    };

    filterSelectedApporve = (array, selected) => {
        const index = array.findIndex((v) => {
            return v['value']['pid'] === selected;
        });
        if (index > -1) {
            const deleted = array.splice(index, 1);
            array.splice(0, 0, deleted[0]);
        }
    };

    getSelectedAnoArray = data => {
        let anoArray = [];
        for (let i = 0; i < data.length; i++ ) {
            anoArray.push(data[i]['ano']);
        }
        this.accessSelectEquip.searchObj.filter_anos = anoArray;
    }

}
